import classNames from 'classnames'
import React, { useEffect, useRef, useState } from 'react'
import { useDispatch } from 'react-redux'
import { changeDone, delTodo, editName } from '../actions/todos'

export default function TodoItem({ item }) {
  const iptRef = useRef()
  const [currentId, setCurrentId] = useState('')
  // 3.若是修改的话不能直接把值给input
  const [name, setName] = useState(item.name)
  //1.处理双击
  const handleClick = (item) => {
    setCurrentId(item.id)
  }
  const dispatch = useDispatch()

  //2. 当currentId 更改时获取焦点
  useEffect(() => {
    iptRef.current.focus()
  }, [currentId])

  // 4. 回车修改
  const edit = (e) => {
    if (e.keyCode === 27) {
      setCurrentId('')
      return
    }
    if (e.keyCode === 13) {
      dispatch(editName(name, currentId))
      setCurrentId('')
    }
  }
  return (
    <li
      className={classNames({
        completed: item.done,
        editing: currentId === item.id,
      })}
    >
      <div className="view">
        <input
          className="toggle"
          type="checkbox"
          checked={item.done}
          onChange={() => dispatch(changeDone(item.id))}
        />
        <label
          onDoubleClick={() => {
            handleClick(item)
          }}
        >
          {item.name}
        </label>
        <button
          className="destroy"
          onClick={() => dispatch(delTodo(item.id))}
        ></button>
      </div>
      <input
        className="edit"
        onBlur={() => setCurrentId('')}
        ref={iptRef}
        value={name}
        onChange={(e) => setName(e.target.value)}
        onKeyUp={edit}
      />
    </li>
  )
}
